/** biome-ignore-all lint/a11y/useKeyWithClickEvents: ignore */
/** biome-ignore-all lint/a11y/noStaticElementInteractions: ignore */
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { useLexicalNodeSelection } from "@lexical/react/useLexicalNodeSelection";
import type { NodeKey } from "lexical";
import { useCallback, useEffect } from "react";

interface VariableChipProps {
  variable: string;
  nodeKey: NodeKey;
}

export function VariableChip({ variable, nodeKey }: VariableChipProps) {
  const [isSelected, setSelected, clearSelection] =
    useLexicalNodeSelection(nodeKey);
  const [editor] = useLexicalComposerContext();

  const handleMouseDown = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();
      clearSelection();
      setSelected(true);
      const elem = editor.getElementByKey(nodeKey);
      if (elem) elem.classList.add("variable-chip-selected");
    },
    [clearSelection, editor, nodeKey, setSelected],
  );

  useEffect(() => {
    const el = editor.getElementByKey(nodeKey);
    if (!el) return;
    el.classList[isSelected ? "add" : "remove"]("variable-chip-selected");
  }, [isSelected, editor, nodeKey]);

  return (
    <span
      className={isSelected ? "variable-chip-selected" : undefined}
      onMouseDown={handleMouseDown}
    >
      {`{{${variable}}}`}
    </span>
  );
}
